package com.ruoyi.generator.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.generator.domain.FromBuildConfig;
import com.ruoyi.generator.service.IFromBuildConfigService;
import com.ruoyi.generator.service.impl.FromBuildConfigServiceImpl;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * 单设计_配置Controller
 *
 * @author XL
 * @date 2022-08-05 12:01:23
 */
@RestController
@RequestMapping("/tool/gen/FromBuildConfig")
public class FromBuildConfigController extends BaseController {
    @Autowired
    private IFromBuildConfigService fromBuildConfigService;

    @Autowired
    private FromBuildConfigServiceImpl fromBuildConfigServiceImpl;

    @Autowired
    private TokenService tokenService;

    /**
     * 获取字段信息
     *
     * @return
     */
    @GetMapping("/init")
    public AjaxResult getFieldInfo() {
        return fromBuildConfigService.getColumnConfigByTableName("sys_from_build_config");
    }

    /**
     * 查询单设计_配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:list')")
    @GetMapping("/list")
    public TableDataInfo list(FromBuildConfig fromBuildConfig) {
        try {
            startPage();
            List<FromBuildConfig> list = fromBuildConfigService.selectFromBuildConfigList(fromBuildConfig);
            return getDataTable(list);
        } catch (Exception e) {
            logger.error("FromBuildConfigController接口list异常", e);
            return null;
        }
    }

    /**
     * 导出单设计_配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:export')")
    @Log(tableName = "sys_from_build_config", title = "单设计_配置", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FromBuildConfig fromBuildConfig) {
        try {
            List<FromBuildConfig> list = fromBuildConfigService.selectFromBuildConfigList(fromBuildConfig);
            ExcelUtil<FromBuildConfig> util = new ExcelUtil<FromBuildConfig>(FromBuildConfig.class);
            return util.exportExcel(list, "FromBuildConfig");
        } catch (Exception e) {
            logger.error("FromBuildConfigController接口export异常", e);
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 导入单设计_配置列表
     */

    /**
     * 获取单设计_配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id,
                              @RequestParam(value = "clientType", defaultValue = "PC") String clientType) {
        try {
            Map<String, Object> result = new HashMap<>();
            //表单数据
            result.put("data", fromBuildConfigService.selectFromBuildConfigById(id));
            //表单设计字段配置信息
            result.put("formBuildConfig", fromBuildConfigService.getFormBuildConfig("FromBuildConfig", clientType));
            //返回结果
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("FromBuildConfigController接口getInfo异常", e);
            return AjaxResult.error("获取异常");
        }
    }

    /**
     * 新增单设计_配置
     */
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:add')")
    @Log(tableName = "sys_from_build_config", title = "单设计_配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FromBuildConfig fromBuildConfig) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            fromBuildConfig.setCreateBy(loginUser.getUsername());
            fromBuildConfig.setCreateTime(new Date());
            return toAjax(fromBuildConfigService.insertFromBuildConfig(fromBuildConfig));
        } catch (Exception e) {
            logger.error("FromBuildConfigController接口add异常", e);
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 修改单设计_配置
     */
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:edit')")
    @Log(tableName = "sys_from_build_config", title = "单设计_配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FromBuildConfig fromBuildConfig) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            fromBuildConfig.setUpdateBy(loginUser.getUsername());
            fromBuildConfig.setUpdateTime(new Date());
            return toAjax(fromBuildConfigService.updateFromBuildConfig(fromBuildConfig));
        } catch (Exception e) {
            logger.error("FromBuildConfigController接口edit异常", e);
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 删除单设计_配置
     */
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:remove')")
    @Log(tableName = "sys_from_build_config", title = "单设计_配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        try {
            return toAjax(fromBuildConfigService.deleteFromBuildConfigByIds(ids));
        } catch (Exception e) {
            logger.error("FromBuildConfigController接口remove异常", e);
            return AjaxResult.error("操作失败");
        }
    }

    @Log(tableName = "sys_from_build_config", title = "单设计_配置", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:FromBuildConfig:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<FromBuildConfig> util = new ExcelUtil<FromBuildConfig>(FromBuildConfig.class);
        List<FromBuildConfig> dataList = util.importExcel(file.getInputStream());
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        String operName = loginUser.getUsername();
        int successCount = 0;
        for (FromBuildConfig item : dataList) {
            successCount += fromBuildConfigService.insertFromBuildConfig(item);
        }
        String result = StringUtils.format("导入成功条数:{}，失败条数：{}", successCount, (dataList.size() - successCount));
        return AjaxResult.success(result);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<FromBuildConfig> util = new ExcelUtil<FromBuildConfig>(FromBuildConfig.class);
        return util.importTemplateExcel("单设计_配置");
    }

    /**
     * ============================================================================
     */

    /**
     * 获取表单设计字段配置信息
     *
     * @param processNodeForm
     * @return
     */
    @PostMapping(value = "/getFormBuildConfig")
    public AjaxResult getFormBuildConfig(@RequestBody Map<String, Object> processNodeForm) {
        if (processNodeForm == null || processNodeForm.size() <= 0) {
            return AjaxResult.error("操作失败，参数获取异常");
        }
        /**
         * 1. 表单设计唯一key
         */
        String formBuildKey = String.valueOf(processNodeForm.get("formBuildKey"));
        /**
         * 终端类型__PC_Mobile
         */
        String clientType = String.valueOf(processNodeForm.get("clientType"));
        if (StringUtils.isEmpty(clientType)) {
            clientType = "PC";
        }
        /**
         * 判断参数是否为空
         */
        if (StringUtils.isEmpty(formBuildKey)) {
            return AjaxResult.error("操作失败，表单编码为空");
        }
        /**
         * 判断formBuildKey是否是以业务模块_菜单ID的形式
         */
        if (formBuildKey.indexOf("_") == -1) {
            /**
             * 判断当前业务表是否对应有多个菜单，如果只有一个则返回对应菜单的表单设计信息，如果有多个则返回最基础的表单设计信息
             */
            /** 根据业务表模块名，获取对应所有的表单设计KEY **/
            List<Map<String, Object>> allFormBuildKeys = fromBuildConfigService.getAllFormBuildKeyByBusinessName(formBuildKey);
            if (allFormBuildKeys != null && allFormBuildKeys.size() == 1) {
                String _formBuildKey = String.valueOf(allFormBuildKeys.get(0).get("formBuildKey"));
                formBuildKey = StringUtils.isEmptyIncludeNull(_formBuildKey) ? formBuildKey : _formBuildKey;
            }
        }
        /**
         * 获取表单配置信息
         */
        List<FromBuildConfig> formBuildConfigInfoList = fromBuildConfigService.getFormBuildConfig(formBuildKey, clientType);
        /**
         * 特殊参数处理
         */
        fromBuildConfigServiceImpl.paramDeal(formBuildConfigInfoList);

        return AjaxResult.success(formBuildConfigInfoList);
    }


}
